package gui;

import gameObjects.Castle;
import gameObjects.Unit;

import javax.swing.JOptionPane;

import castlewarserver.Connector;

public class WaitingThread implements Runnable {

	Connector connector;
	MainWindow mainWindow;

	public WaitingThread(Connector connector, MainWindow mainWindow){
		this.connector = connector;
		this.mainWindow = mainWindow;
	}
	@Override
	public void run() {

		while (true){
			if (connector.isEndOfGame()){
				mainWindow.endOfGame();
				break;
			}
			String actualPlayer = connector.getActualPlayer();
			// update units and castles
			updateCastles();
			updateUnits();
			mainWindow.drawAllGuiObjects();
			Castle castle;
			if (mainWindow.player.equalsIgnoreCase("ORANGE")){
				castle = (Castle)mainWindow.castleOrange.getGameObject();
			}
			else{
				castle = (Castle)mainWindow.castleBlue.getGameObject();
			}

			mainWindow.goldLabel.setText(String.valueOf(castle.getGold()));
			mainWindow.castleHpLabel.setText(String.valueOf(castle.getHp()));

			mainWindow.layeredPane.repaint();

			if (actualPlayer.equalsIgnoreCase(mainWindow.player)){
				mainWindow.actualPlayer=actualPlayer;
				mainWindow.endTurnButton.setEnabled(true);
				JOptionPane.showMessageDialog(mainWindow.mainFrame, "Your turn");
				break;
			}


			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	}

	private void updateUnits(){
	
		Unit newUnits [] = connector.getAllUnits();

		for (GuiObject guiObj:mainWindow.units){
			mainWindow.layeredPane.remove(guiObj);
		}

		mainWindow.units.clear();

		for(int i = 0; i < newUnits.length; i++){
			mainWindow.units.add(new GuiObject(newUnits[i]));
		}

	}

	private void updateCastles(){

		mainWindow.castleBlue.setGameObject(connector.getCastle("BLUE"));
		mainWindow.castleOrange.setGameObject(connector.getCastle("ORANGE"));
	}
}
